<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/**
 * Description: 封装常用函数
 *
 * @author      Eden
 * @datetime    2016/12/6 09:41
 * @copyright   Beijing CmsTop Technology Co.,Ltd.
 */
require_once FCPATH . '/application/third_party/alipay/AopSdk.php';

function local($file)
{
    $extInfo = explode('.', $file['name']);
    $ext = end($extInfo);
    $filepath = '/a/' . date('Y/m') . '/';
    $filename = md5(uniqid()) . ($ext ? ('.' . $ext) : '');
    $aurl = $filepath . $filename;
    $filesize = !empty($file['size']) ? intval($file['size']) : 0;
    $imageInfo = getimagesize($file['tmp_name']);
    $width = $imageInfo[0] ? intval($imageInfo[0]) : 0;
    $height = $imageInfo[1] ? intval($imageInfo[1]) : 0;
    $filemime = $imageInfo['mime'] ?: '';
    $fileData = file_get_contents($file['tmp_name']);

    if (empty($width) || empty($height) || empty($fileData)) {
        return false;
    }

    $ci = &get_instance();
    $ci->load->library('core/Beansdb.php', 'beansdb');
    if (!$ci->beansdb->save($aurl, $fileData)) {
        return false;
    }
    $data = array();
    $data['filePath'] = $filepath;
    $data['fileName'] = $filename;
    $data['alias'] = $file['name'];
    $data['ext'] = $ext;
    $data['size'] = $filesize;
    $data['width'] = $width;
    $data['height'] = $height;
    $data['mime'] = $filemime;

    try {
        $ci->db->insert('attachment', array_merge($data, array('fullPath' => $aurl)));
    } catch(PDOException $e) {}

    return array(
        'key' => $aurl,
        'data' => $data
    );
}

/**
 * 获取图片访问地址
 * @param $path
 * @param int $width
 * @param int $height
 * @return mixed|string
 */
function thumb($path, $width = 0, $height = 0)
{
    if (empty($path)) {
        return '';
    }

    // 如果是链接
    if (strpos($path, 'http') === 0) {
        return $path;
    }

    if (empty($width) && empty($height)) {
        return rtrim(IMG_URL, '/') . '/' . ltrim($path, '/');
    }
    $ext = pathinfo($path, PATHINFO_EXTENSION);
    $path = str_replace('/a/', '/a/thumb/', $path);
    return rtrim(IMG_URL, '/') . '/' . ltrim($path, '/') . '@w' . $width . '_h' . $height . '.' . $ext;
}

/**
 * BBS 图片列表
 * @param $attachments
 * @param string $type
 * @return array
 */
function bbsThumb($attachments, $type = 'android', $width = 0, $height = 0)
{
    if (is_string($attachments)) {
        try {
            $attachments = json_decode($attachments, true);
            if (!is_array($attachments)) {
                return array(
                    'thumb' => array(),
                    'org' => array()
                );
            }
        } catch (Exception $e) {}
    }

    $thumbs = array();
    $orgs = array();
    foreach ($attachments as $attach) {
        if (empty($attach)) {continue;}

        $width = empty($width) ? 100 : $width;
        $height = empty($height) ? 100 : $height;

        if ($type == 'ios') {
            array_push($thumbs, thumb($attach, $width * 2, $height * 2));
        } else {
            array_push($thumbs, thumb($attach, $width, $height));
        }
        array_push($orgs, thumb($attach));
    }

    return array(
        'thumb' => $thumbs,
        'org' => $orgs
    );
}

/**
 * 写文件
 * @param $file
 * @param $data
 * @param bool|false $append
 * @param bool|false $flock
 * @return bool|int
 */
function writeFile($file, $data, $append = false, $flock = false)
{
    try {
        $dir = dirname($file);
        if (!is_dir($dir)) {
            mkdir($dir, 0777, true);
        }

        $fp = fopen($file, ($append ? 'ab' : 'wb'));
        if (empty($fp)) {
            $res = false;
        } else {
            if ($flock) {
                flock($fp, LOCK_EX);
            }

            $res = fwrite($fp, $data);

            if ($flock) {
                flock($fp, LOCK_UN);
            }

            fclose($fp);
            chmod($file, 0777);
        }

        return $res;
    } catch(Exception $e) {
        echo $e->getMessage();die;
    }
}

/**
 * 请求远程接口
 * @param $url
 * @param array $params
 * @param string $method
 * @param array $multipart
 * @param array $extra_headers
 * @return array
 */
function request($url, $params = array(), $method = 'GET', array $multipart = array(), array $extra_headers = array())
{
    $method = strtoupper($method);
    $curl = curl_init();
    $headers = (array)$extra_headers;
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    switch ($method) {
        case 'POST':
            curl_setopt($curl, CURLOPT_POST, true);
            if (!empty($params)) {
                curl_setopt($curl, CURLOPT_POSTFIELDS, is_array($params) ? http_build_query($params) : $params);
            }
            break;
        case 'DELETE':
        case 'GET':
            if ($method == 'DELETE') {
                curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'DELETE');
            }
            if (!empty($params)) {
                $url = $url . (strpos($url, '?') !== false ? '&' : '?')
                    . (is_array($params) ? http_build_query($params) : $params);
            }
            break;
    }

    curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($curl, CURLOPT_URL, $url);
    $response = curl_exec($curl);
    $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
    $httpInfo = curl_getinfo($curl) ?: array();
    curl_close($curl);

    return array(
        'data' => $response,
        'httpCode' => $httpCode,
        'httpInfo' => $httpInfo
    );
}

/**
 * 生成阿里签名
 * @param $data
 * @return string
 * @throws Exception
 */
function alipay_sign($data)
{
    $c = new AopClient;
    $c->gatewayUrl = ALIPAY_GATEWAY_URL;
    $c->appId = ALIPAY_APPID;
    $c->rsaPrivateKey = ALIPAY_RSA_PRIVATE_KEY;
    $c->format = ALIPAY_FORMAT;
    $c->charset= ALIPAY_CHARSET;
    $c->alipayrsaPublicKey = ALIPAY_RSA_PUBLIC_KEY;

    $request = new AlipayTradeAppPayRequest();

    if (empty($data['body']) || empty($data['subject']) || empty($data['out_trade_no'])
        || empty($data['total_amount'])) {
        return '';
    }


    $data['product_code'] = 'QUICK_MSECURITY_PAY';

    try {

        $biz = '{';
        foreach($data as $k => $d) {
            $biz .= '"' . $k . '":"' . $d . '",';
        }
        $biz = rtrim($biz, ',');
        $biz .= '}';

        $request->setNotifyUrl(ALIPAY_CALLBACK_URL);
        $request->setBizContent($biz);
        return $c->sdkExecute($request);
    } catch(Exception $e) {
        throw new Exception('签名错误');
    }
}

/**
 * 支付宝验签
 * @param array $posts
 * @return bool
 */
function alipay_verify(Array $posts)
{
    $c = new AopClient;
    $c->gatewayUrl = ALIPAY_GATEWAY_URL;
    $c->appId = ALIPAY_APPID;
    $c->rsaPrivateKey = ALIPAY_RSA_PRIVATE_KEY;
    $c->format = ALIPAY_FORMAT;
    $c->charset= ALIPAY_CHARSET;
    $c->alipayrsaPublicKey = ALIPAY_RSA_PUBLIC_KEY;

    return $c->rsaCheckV1($posts, '');
}

function wxPayUnifiedorder($user, $goods, $notifyUrl, $type = 'JSAPI', $desc = '购买黄桃')
{

    $domain = env('DEFINE.WX_URL');
    $notifyUrl = rtrim($domain, '/') . '/wechatnotify/' . ltrim($notifyUrl, '/');

    $extra = $cashin = array();
    $extra['userid'] = $user['id'];
    $extra['state'] = 0;                                        // 支付状态
    $extra['transaction_id'] = '';                              // 交易单号,支付完成回调生效

    $cashin['appid'] = $this->wechat['appid'];
    $cashin['mch_id'] = $this->pay['mchid'];
    $cashin['device_info'] = 'WAP';                             // 设备号
    $cashin['nonce_str'] = strtoupper(md5(uniqid()));
    $cashin['body'] = $goods['detail'];                         // 描述
    $cashin['detail'] = json_encode($goods);                    // json
    $cashin['attach'] = $desc;                                  // 可选
    $cashin['out_trade_no'] = $this->generateTradeNo();         // 商户订单号
    $cashin['total_fee'] = intval($goods['amount']);   // 总金额,单位分
    $cashin['spbill_create_ip'] = get_client_ip();              // 用户IP
    $cashin['goods_tag'] = '黄桃';                               // #
    $cashin['notify_url'] = $notifyUrl;                         // 异步接收微信支付回调的地址
    $cashin['trade_type'] = $type;                              // jsapi  jsapi | native | app
    $cashin['product_id'] = $goods['id'];                       // # 商品ID,需要二维码是必须
    $cashin['openid'] = $user['openid'];                        // #

    try {

        $cashid = model('user_buy')->data(array_merge($cashin, $extra))->add();
        if ($cashid) {

            $cashin['sign'] = $this->sign($cashin);
            $this->cachin = $cashin;
            $xml = array2xml($cashin, 'xml');
            $result = $this->http_post(self::API_URL_PREFIX . self::UNIFIEDORDER, $xml);
            if ($result) {
                $result = (array)simplexml_load_string($result, 'SimpleXMLElement', LIBXML_NOCDATA);
                if ($result['return_code'] === 'SUCCESS') {
                    if ($result['result_code'] === 'SUCCESS') {

                        // 这里是 JSSDK需要用的
                        $this->prepay_id = $prepayid = $result['prepay_id'];
                        $this->jsapi['appId'] = $this->wechat['appid'];
                        $this->jsapi['timeStamp'] = strval(time());
                        $this->jsapi['nonceStr'] = substr(md5(uniqid()), 0, 8);
                        $this->jsapi['package'] = 'prepay_id='.$prepayid;
                        $this->jsapi['signType'] = 'MD5';
                        $this->jsapi['paySign'] = $this->sign($this->jsapi);

                        $update = array();
                        $update['state'] = 1;
                        $update['prepay_id'] = $prepayid;
                        $update['code_url'] = isset($result['code_url']) ? $result['code_url'] : "";
                        model('user_buy')->where(array('id' => $cashid))->data($update)->save();

                        return true;
                    } else {
                        $this->error = !empty($result['return_msg']) ? $result['return_msg'] : '业务支付失败';
                    }
                } else {
                    $update = array();
                    $update['err_code'] = isset($result['return_code']) ? $result['return_code'] : '';
                    $update['err_code_des'] = $this->error = isset($result['return_msg']) ? $result['return_msg'] : '';
                    $update['state'] = 5;
                    model('user_buy')->where(array('id'=>$cashid))->data($update)->save();
                }
            } else {
                $update = array();
                $update['state'] = 5;
                $this->error = '充值失败';
                model('user_buy')->where(array('id'=>$cashid))->data($update)->save();
            }
        }

    } catch (Exception $e) {
        $this->error = '充值失败';
    }

    return false;
}
